package com.netty.demo.fundamental.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author shengtao
 * @Description:
 * @date 2018/09/06 12:04
 */
public class EchoClinetHandler extends ChannelHandlerAdapter{

    private final ByteBuf firstMessage;

    public EchoClinetHandler() {
        firstMessage = Unpooled.buffer(EchoClinet.SIZE);
        for (int i=0;i<firstMessage.capacity();i++){
            firstMessage.writeByte(i++);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("====================================client userEventTriggered==================");
    }
}
